<?php

namespace app\admin\logic;

use support\Backend\BackendLogic;
use support\Container;
use support\Exception\ApiException;
use support\Service\MemberService;

class MemberLogic extends BackendLogic
{

    public function __construct()
    {
        $this->service = Container::get(MemberService::class);
    }

    public function getList(): array
    {
        $param = request()->get();
        $where[] = ["mark", '=', 1];
        if (isset($param['id']) && $param['id']) {
            $where[] = ["id", '=', (int)$param['id']];
        }
        if (isset($param['username']) && $param['username']) {
            $where[] = ["username", 'like', "%{$param['username']}%"];
        }
        if (isset($param['nickname']) && $param['nickname']) {
            $where[] = ["nickname", 'like', "%{$param['nickname']}%"];
        }
        if (isset($param['phone']) && $param['phone']) {
            $where[] = ["phone", '=', $param['phone']];
        }
        if (isset($param['create_time']) && $param['create_time']) {
            $where[] = ["create_time", '>=', strtotime($param['create_time'][0])];
            $where[] = ["create_time", '<=', strtotime($param['create_time'][1])];
        }
        $list = $this->service->getListPage($where, ['*'], ['id' => 'desc'], ['memberAccount']);

        if ($list['total'] <= 0) return message($list);
        foreach ($list['list'] as $k => $item) {
            $item['balance'] = $item['member_account']['balance'] ?? 0;
            $item['integral'] = $item['member_account']['integral'] ?? 0;
            unset($item['member_account']);
            $list['list'][$k] = $item;
        }
        return message($list);
    }

    public function edit(): array
    {

        $data = request()->post();
        $id = $data['id'] ?? 0;
        if (empty($data['status'])) throw new ApiException('请选择状态');
        $save['status'] = $data['status'];
        $save['nickname'] = $data['nickname'] ?? 1;
        unset($data['id']);
        if (!$id) {
            if (isset($data['password']) && $data['password']) {
                $save['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }
        } 
        if ($id == 0) {
            $this->service->add($save);
        } else {
            $this->service->save($save, $id);
        }
        return message();

    }





}
